from src.util.Service import *


# 获取所有的字典(分页 所有信息)
def getDictAll(page: Page = Page(), cdn: dict = None):
    if cdn is None:
        cdn = dict()
    Dicts = Dict.getAllDict(page, cdn)
    return Dicts


# 根据path type获取所有的字典的键值对
def getDictPathTypeKv(path, d_type):
    d: dict = Dict.getDictByPathAndTYpe(path, d_type)
    if d is None:
        return []
    if d.get('status') != '1':
        return []
    Dicts = DictKeyValue.getKvByDid(d.get('dId'))
    return Dicts


# 修改字典（除了did）
def updateDict(k: dict):
    try:
        id = k['dId']
        k = formatParam(k, ['dId', 'initTime'])
        """ 参数校验 """
        Dict.updateDict(id, k)
        return True
    except:
        return False


# 删除字典
def delDict(d_ids: list[int]):
    database.transaction()
    try:
        with database.atomic():
            DictKeyValue.delDictKeyValueByDid(d_ids)
            Dict.delDictById(d_ids)
            database.commit()
    except:
        database.rollback()
        return False
    return True


# 添加字典（除了did）
def addDict(data: dict):
    data['status'] = '1'
    data['initTime'] = datetime.utcnow()
    try:
        Dict.addDict(data)
        return True
    except:
        return False


# 更新字典所有键值对
def updateAllKeyVal(data: list[dict], did: int):
    try:
        database.transaction()
        with database.atomic():
            for d in data:
                d['dId'] = did
            DictKeyValue.delDictKeyValueByDid([did])
            DictKeyValue.addDictKv(data)
            database.commit()
            return True
    except:
        database.rollback()
        return False


# 根据字典id 获取 字典所有键值
def getDictAllKeyVal(did: int):
    return DictKeyValue.getKvByDid(did)
